package com.example.demo;

import com.example.demo.httpMessageConvert.*;
import com.example.demo.httpMessageConvert.weixin.AccessToken;
import com.example.demo.httpMessageConvert.weixin.Event;
import com.example.demo.httpMessageConvert.weixin.Message;
import com.example.demo.httpMessageConvert.weixin.MsgType;
import com.example.demo.httpMessageConvert.weixin.menu.Button;
import com.example.demo.httpMessageConvert.weixin.menu.ClickButton;
import com.example.demo.httpMessageConvert.weixin.menu.Menu;
import com.example.demo.httpMessageConvert.weixin.menu.ViewButton;
import com.example.demo.httpMessageConvert.weixin.message.*;
import com.example.demo.util.WeixinUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/7/31.
 */
@Controller
@RequestMapping("weixin")
public class WeiXinController {
    private static Log logger = LogFactory.getLog(WeiXinController.class);
    @Autowired
    private Property property;
    @Autowired
    private WeixinUtil weixinUtil;
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    private static HttpClient httpClient = HttpClients.createDefault();

    @RequestMapping(value = "weixin.do", method = RequestMethod.GET)
    public void weixinGet(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, NoSuchAlgorithmException {
        String signature = httpServletRequest.getParameter("signature");
        String timestamp = httpServletRequest.getParameter("timestamp");
        String nonce = httpServletRequest.getParameter("nonce");
        String echostr = httpServletRequest.getParameter("echostr");
        PrintWriter pw = httpServletResponse.getWriter();
        String[] strs = {property.getToken(), nonce, timestamp};
        Arrays.sort(strs);
        StringBuffer sb = new StringBuffer();
        for (String string : strs) {
            sb.append(string);
        }
        String s = String.valueOf(Hex.encode(MessageDigest.getInstance("SHA-1").digest(StringUtils.getBytesUtf8(sb.toString()))));
        if (s.equals(signature)) {
            pw.print(echostr);
        }
        pw.close();
    }

    @RequestMapping(value = "weixin.do", method = RequestMethod.POST)
    @ResponseBody
    public Message weixinPost(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody Message message) throws IOException, JAXBException {
        // 发送时间
        message.setCreateTime(System.currentTimeMillis());
        // 发送人和接受人交换
        String temToUserName = message.getToUserName();
        message.setToUserName(message.getFromUserName());
        message.setFromUserName(temToUserName);
        if (message.getMsgType() == MsgType.text) {
            if ("image".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.image);
                Image image = new Image();
                image.setMediaId("O3BgMsNYwG7ERnnXTp28qqUGZpqDpkeLbLdJdwg3jMIWPaVLNKHvouDmO5Wd4qLQ");
                message.setImage(image);
            } else if ("music".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.music);
                Music music = new Music();
                music.setThumbMediaId("cIB7znE0VCwxwBR8pCCDGkv8LtaLvSp8HS4hi5LIXHNtJ1bvwif_9eyxAVdVJv1U");
                music.setTitle("see you again");
                music.setDescription("速7片尾曲");
                music.setMusicUrl("http://tangxinmao.yicp.io/resources/music/See You Again.mp3");
                music.setHQMusicUrl("http://tangxinmao.yicp.io/resources/music/See You Again.mp3");
                message.setMusic(music);
            } else if ("video".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.video);
                Video video = new Video();
                video.setTitle("see you again");
                video.setDescription("速7片尾曲");
                video.setMediaId("MmYMN0ME8F2h1wx6g6Ry71A7QFFfEEwFoEtvig98mn2QKXvNaQcN8tOda-gjPI56");
                message.setVideo(video);
            } else if ("voice".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.voice);
                Voice voice = new Voice();
                voice.setMediaId("toW3hMzyjWqIIszpkD3mVwK4nkKljo3acPNcWG0SDYHYyN-IAZ-I0qgomzFZT6D_");
                message.setVoice(voice);
            } else if ("news".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.news);
                Item i = new Item();
                i.setDescription("回复image 或者 news");
                i.setPicUrl("http://tangxinmao.yicp.io/resources/image/006.png");
                i.setTitle("该账号仅用于测试！");
                i.setUrl(property.getAuthorize() + "?appid=" + property.getAppid() + "&redirect_uri=" + URLEncoder.encode(property.getRedirect_uri(), "utf-8") + "&response_type=code&scope=snsapi_userinfo&state=" + UUID.randomUUID());
                List<Item> l = new ArrayList<Item>();
                l.add(i);
                message.setArticles(l);
                message.setArticleCount(l.size());
            }
        }
        if (message.getMsgType() == MsgType.event) {
            if (message.getEvent() == Event.subscribe) {
                message.setMsgType(MsgType.news);
                Item i = new Item();
                i.setDescription("回复image 或者 news");
                i.setPicUrl("http://tangxinmao.yicp.io/resources/image/006.png");
                i.setTitle("该账号仅用于测试！");
                i.setUrl("http://tangxinmao.yicp.io");
                List<Item> l = new ArrayList<Item>();
                l.add(i);
                message.setArticles(l);
                message.setArticleCount(l.size());

            } else if (message.getEvent() ==
                    Event.unsubscribe) {
                message.setMsgType(MsgType.text);
                message.setContent("下次再来额！");
            } else if (message.getEvent() == Event.CLICK) {
                message.setMsgType(MsgType.text);
                message.setContent("欢迎光林！");
            } else if (message.getEvent() == Event.VIEW) {
            } else if (message.getEvent() == Event.scancode_push) {


            }

        }
        if (message.getMsgType() == MsgType.location) {
            message.setMsgType(MsgType.text);
            message.setContent(message.getLabel());
        }
        return message;
    }

    /**
     * 微信授权登陆接口
     *
     * @param code
     * @return
     * @throws IOException
     */
    @GetMapping(value = "code")
    public String index(String code, HttpSession httpSession,String state) throws IOException {
       if( redisTemplate.opsForHash().hasKey(RedisKey.CODE_STATE,code)&&redisTemplate.opsForHash().get(RedisKey.CODE_STATE,code).equals(state)) {
           redisTemplate.boundHashOps(RedisKey.CODE_STATE).delete(code);
           AccessToken accessTokenUser = weiXinService.getAccessToken(code);
           if(accessTokenUser==null){
               return "redirect:/test/home";
           }else{
               UserInfo userInfo = weiXinService.getUserInfo(accessTokenUser);
               httpSession.setAttribute(SessionKey.USER_INFO, userInfo);
           }

       }else{
           redisTemplate.boundHashOps(RedisKey.CODE_STATE).put(code,state);
           AccessToken accessTokenUser = weiXinService.getAccessToken(code);
           if(accessTokenUser==null){
               return "redirect:/test/home";
           }else{
               UserInfo userInfo = weiXinService.getUserInfo(accessTokenUser);
               httpSession.setAttribute(SessionKey.USER_INFO, userInfo);
           }
       }
        return "redirect:/test/home";
    }



    @GetMapping(value = "menuCreate")
    @ResponseBody
    public Err menuCreate() throws Exception {
        Menu menu = new Menu();
        ViewButton button21 = new ViewButton();
        button21.setName("Demo音乐");
        button21.setType("view");
        button21.setUrl("http://1548i94i39.iok.la/txm/test/home");

        ClickButton button31 = new ClickButton();
        button31.setName("扫码事件");
        button31.setType("scancode_push");
        button31.setKey("31");
        ClickButton button33 = new ClickButton();
        button33.setName("扫码返回");
        button33.setType("scancode_waitmsg");
        button33.setKey("33");
        ClickButton button32 = new ClickButton();
        button32.setName("地理位置");
        button32.setType("location_select");
        button32.setKey("32");
        Button button = new Button();
        button.setName("菜单");
        button.setSub_button(new Button[]{button31, button32, button33});
        menu.setButton(new Button[]{button21, button});
        Err err = weiXinService.menuCreate(menu);
        return err;
    }


}
